/**
 * File: ShortReadGraphLoadController.java
 * Created by: mhaimel
 * Created on: Apr 20, 2010
 * CVS:  $Id: ShortReadGraphLoadController.java 1.0 Apr 20, 2010 9:37:39 AM mhaimel Exp $
 */
package uk.ac.ebi.curtain.controller.loader;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import uk.ac.ebi.curtain.controller.ParallelController;
import uk.ac.ebi.curtain.controller.SimpleReport;
import uk.ac.ebi.curtain.management.IControllerReport;
import uk.ac.ebi.curtain.management.InterceptorInfo;
import uk.ac.ebi.curtain.processor.load.impl.ShortReadGraphLoadProcessor;
import uk.ac.ebi.curtain.util.io.MapEntryWriter;
import uk.ac.ebi.curtain.utils.CurtainUncheckedException;
import uk.ac.ebi.curtain.utils.concurrent.UtilsCollect;
import uk.ac.ebi.curtain.utils.data.DataEntry;
import uk.ac.ebi.curtain.utils.data.ReadType;
import uk.ac.ebi.curtain.utils.io.impl.FileIO;

/**
 * @author mhaimel
 *
 */
public class ShortReadGraphLoadController extends ParallelController<DataEntry<File>, String, ShortReadGraphLoadProcessor> {
	private Integer iCnt = 0;
	private static final Object _LOCK_OBJ = new Object();
	private final ConcurrentMap<ReadType, MapEntryWriter> mewMap = UtilsCollect.newConcurrentMap();


	@Override
	protected ShortReadGraphLoadProcessor buildJob(DataEntry<File> input, InterceptorInfo info) {
		++iCnt;
		ShortReadGraphLoadProcessor loader = getContext().getInjector().getInstance(ShortReadGraphLoadProcessor.class);
		loader.setMapEntryWriter(getWriter(input.getMetaData().getReadType()));
		return loader;
	}
	
	private MapEntryWriter getWriter(ReadType readType) {
		synchronized (_LOCK_OBJ) {
			MapEntryWriter writer = mewMap.get(readType);
			if(null == writer){
				writer = new MapEntryWriter(getPrintWriter(readType));
				mewMap.put(readType, writer);
			}
			return writer;
		}
	}

	private PrintWriter getPrintWriter(ReadType readType)  {
		File file = getContext().currentFiles().getEntryMapPosition(readType);
		try {
			return new FileIO(file,true).getPrintWriter();
		} catch (IOException e) {
			throw new CurtainUncheckedException("Problems open file " + file,e);
		}
	}

	@Override
	protected void doShutdown() {
		for(MapEntryWriter w : mewMap.values()){
			FileIO.closeQuietly(w);
		}
		getLog().debug("Build Arc index ...");
		getContext().getGraph().getGraph().buildArcsIndex();
		getContext().getGraph().getGraph().reindexArcs();
		super.doShutdown();
	}

	@Override
	protected IControllerReport getReturnCall() {
		return new SimpleReport("Finished loading " + iCnt + " match files!");
	}

}
